<?php

namespace PipProcess;

use Config\Main;
use Library\Core\Config;
use Model\Settings\SettingsModel;
use ZScript\Process\Process as ZScriptProcess;

/**
 * Class Dispense
 * @package PipProcess
 */
class Dispense extends ZScriptProcess
{
    /**
     * 进程开启后的回调
     * @param \swoole_process $process
     * @author soosoogoo
     * ------------------------------------------------------------------
     */
    public function onStart(\swoole_process $process)
    {
        //设置进程名称
        $process->name(Main::$projectName . "-sws-swoole-fork-process");

        // 初始化删除 work配置
        Config::delWorkerConfig();

        // 分配 worker 任务
        self::saveWorkConfig();

        sleep(1);

        // 初始杀进程
        //\Library\Kill::reloadWorker();

        // 分配任务
        \swoole_timer_tick(10000, [self::class, 'saveWorkConfig']);

        // todo 每10分钟 定时重启 可自定义
        \swoole_timer_tick(1000 * 600, [\Library\Kill::class, 'reloadWorker']);
    }

    /**
     * 启动子进程,分配任务
     * 此处要在main处实现 jobs 方法
     * @author soosoogoo
     * ------------------------------------------------------------------
     */
    public static function saveWorkConfig()
    {
        //echo date('Y/m/d H:i:s'), ' ', __CLASS__, ' 定时子进程,分配任务', PHP_EOL;

        // 获取任务
        $taskList = Main::dispense()->taskDispense();

        if($taskList)
        {
            $workerNum = Main::$swooleSettins['worker_num'];

            $i = 0;
            foreach ($taskList as $job) {
                $workId = $i++ % ($workerNum - 1);
                Config::saveWorkConfig($workId, $job);
            }
        }


        \swoole_timer_tick(1000, function () {

            SettingsModel::cacheTimestamp();
        });


    }

    /**
     * 关闭回调
     * @return mixed|void
     * @author soosoogoo
     * ------------------------------------------------------------------
     */
    public function onShutDown()
    {
        //必须为false，非阻塞模式
        while ($ret = \swoole_process::wait(false)) {
            echo "\n\n\n\n\n\n\n\n\n  -------------------onShutDown-------------------------- \n\n\n\n\n\n\n\n\n";
        }
        // TODO: Implement onShutDown() method.
    }

}